package com.leantech.android.browser

import android.app.Application
import android.content.res.Configuration
import coil.ImageLoader
import coil.ImageLoaderFactory
import com.cscj.android.repository.repositoryModule
import com.cscj.android.repository.settings.Settings
import com.cscj.android.repository.settings.model.SettingConstants
import com.leantech.android.browser.skin.SkinManager
import com.cscj.android.utils.LOG
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.runBlocking
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidFileProperties
import org.koin.android.ext.koin.androidLogger
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import org.koin.core.logger.Level


class App : Application(), ImageLoaderFactory, KoinComponent {

    private val appInitial: AppInitial by inject()

    private val imageLoader: ImageLoader by inject()

    private val browserSetting by inject<Settings.BrowserSetting>()

    override fun newImageLoader(): ImageLoader {
        return imageLoader
    }

    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidLogger(Level.DEBUG)
            androidContext(this@App)
            androidFileProperties("ad.properties")
            if (BuildConfig.DEBUG) {
                androidFileProperties("host_debug.properties")
            } else {
                androidFileProperties("host.properties")
            }
            androidFileProperties("app_config.properties")

            modules(appModule, repositoryModule)
        }

        appInitial.init(this)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val darkMode = runBlocking { browserSetting.darkModeFlow().firstOrNull() }
        if (darkMode == SettingConstants.DarkModeFollowSystem) {
            when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
                Configuration.UI_MODE_NIGHT_YES -> {
                    SkinManager.changeSkin(this.applicationContext, SkinManager.SkinDark)
                    LOG.d("Skin", "uiMode change to NightMode")
                }

                Configuration.UI_MODE_NIGHT_NO -> {
                    SkinManager.changeSkin(this.applicationContext, SkinManager.SkinDefault)
                    LOG.d("Skin", "uiMode change to NoNightMode")
                }
            }
        }
    }

}